package cn.jetpiece.cloud.config;

import cn.jetpiece.cloud.config.properties.JetpieceGatewayProperties;
import cn.jetpiece.cloud.core.exception.aop.GatewayExceptionHandler;
import cn.jetpiece.cloud.modular.cache.ResourceServiceCache;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * 网关全局配置
 *
 * @author XuJZ
 * @since 2020/3/6
 */
@Configuration
public class ContextConfig {

    @Bean
    @ConfigurationProperties(prefix = JetpieceGatewayProperties.PREFIX)
    public JetpieceGatewayProperties jetpieceGatewayProperties() {
        JetpieceGatewayProperties jetpieceGatewayProperties = new JetpieceGatewayProperties();
        jetpieceGatewayProperties.setInstance(jetpieceGatewayProperties);
        return jetpieceGatewayProperties;
    }

    /**
     * 请求号header过滤器
     */
    @Bean
    public ResourceServiceCache resourceServiceCache() {
        ResourceServiceCache resourceServiceCache = new ResourceServiceCache();
        resourceServiceCache.setINSTANCE(resourceServiceCache);
        return resourceServiceCache;
    }

    /**
     * 全局错误拦截器
     */
    @Bean
    public GatewayExceptionHandler gatewayExceptionHandler() {
        return new GatewayExceptionHandler();
    }

    /**
     * 跨域过滤器
     */
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}

